<template>
  <view class="questionnairePage">
    <!-- 导航栏 -->
    <view class="top">
      <s-nav-bar title="问卷管理" :background="'transparent'" :titleStyle="{ color: '#ffff', fontWeight: 'bold' }" statusBar
        immersive back :backStyle="{ color: '#fff' }">
        <view slot="right" @click="showCreatePopup">
          <s-icon name="plus" color="#fff" size="20"></s-icon>
        </view>
      </s-nav-bar>

      <!-- 顶部区域 -->
      <view class="info">
        <view class="info-right">
          <view class="name">问卷管理</view>
          <view class="company">共 {{ total }} 份问卷</view>
        </view>
      </view>
    </view>
    <view class="tabContainer">
      <!-- 标签栏 -->
      <s-tabs v-model="activeTab" :list="tabs" activeColor="var(--v-theme)" color="#333"
        :background="'rgba(255,255,255,.95)'" :showLine="true" :border="true"></s-tabs>
    </view>
    <!-- 主内容区域 -->
    <scroll-view class="main" scroll-y="true">
      <!-- 问卷列表 -->
      <view class="listBox" v-if="activeTab === 0">
        <view class="questionnaireList">
          <questionnaire-card v-for="item in questionnaireList" :key="item.id" :item="item"
            :show-menu="showMoreMenu === item.id" @edit="editQuestionnaire" @edit-page="goToEditPage"
            @preview="previewQuestionnaire" @toggle-menu="toggleMoreMenu" @share="share" @copy="copyQuestionnaire"
            @rename="renameQuestionnaire" @delete="deleteQuestionnaire" />

          <view class="emptyTips" v-if="questionnaireList.length === 0">
            <s-icon name="box" size="40" color="#ccc" />
            <view class="emptyText">暂无问卷数据</view>
          </view>
        </view>
      </view>

      <!-- 问卷收集 -->
      <view class="listBox" v-if="activeTab === 1">
        <answer-list />
      </view>

      <!-- 问卷模板 -->
      <view class="listBox" v-if="activeTab === 2">
        <view class="templateList">
          <template-card v-for="template in templates" :key="template.id" :item="template" @preview="previewTemplate"
            @use="useTemplate" />

          <view class="emptyTips" v-if="templates.length === 0">
            <s-icon name="box" size="40" color="#ccc" />
            <view class="emptyText">暂无模板数据</view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 创建问卷按钮 -->
    <view class="createBtnFixed" @click="showCreatePopup" v-if="activeTab === 0">
      <s-icon name="plus" color="#fff" size="20"></s-icon>
      <text>创建问卷</text>
    </view>

    <!-- 创建/编辑问卷弹窗 -->
    <questionnaire-form :show="showFormPopup" :is-edit="isEdit" :loading="loading" :initial-data="formData"
      @cancel="showFormPopup = false" @submit="handleSubmit" />

    <!-- 重命名弹窗 -->
    <rename-popup ref="renamePopup" :show.sync="renameShow" title="重命名问卷" :loading="renameLoading"
      :initial-value="renameValue" @confirm="handleRenameConfirm" @cancel="handleRenameCancel" />

    <!-- 复制问卷弹窗 -->
    <copy-popup ref="copyPopup" :show.sync="copyShow" :title="copyTemplate ? '从模板复制' : '复制问卷'" :loading="copyLoading"
      :initial-value="copyValue" @confirm="handleCopyConfirm" @cancel="handleCopyCancel" />
  </view>
</template>

<script>
import QuestionnaireCard from "./parts/QuestionnaireCard.vue";
import TemplateCard from "./parts/TemplateCard.vue";
import QuestionnaireForm from "./parts/QuestionnaireForm.vue";
import RenamePopup from "./parts/RenamePopup.vue";
import CopyPopup from "./parts/CopyPopup.vue";
import AnswerList from "./parts/AnswerList.vue";

export default {
  components: {
    QuestionnaireCard,
    TemplateCard,
    QuestionnaireForm,
    RenamePopup,
    AnswerList,
    CopyPopup,
  },
  data() {
    return {
      activeTab: 0,
      tabs: [
        { label: "我的问卷", value: 0 },
        { label: "问卷收集", value: 1 },
        { label: "问卷模板", value: 2 },
      ],
      questionnaireList: [],
      templates: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,

      showFormPopup: false,
      isEdit: false,
      loading: false,
      showMoreMenu: null,
      formData: {
        id: "",
        title: "",
        description: "",
      },

      renameShow: false,
      copyShow: false,
      renameLoading: false,
      copyLoading: false,
      currentItem: null,
      copyTemplate: false,
      renameValue: "",
      copyValue: "",
    };
  },
  created() {
    uni.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });

    this.getQuestionnaireList();
    this.loadTemplates();
  },

  methods: {
    // 获取问卷列表
    getQuestionnaireList() {
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize,
      };

      this.sjuAjax.get("/questionnaire/list", params, (res) => {
        if (res && res.code === 200) {
          this.questionnaireList = res.data.list;
          this.total = res.data.pagination.total;
        }
      });
    },

    // 获取模板列表
    loadTemplates() {
      this.sjuAjax.get("/questionnaire/templates", {}, (res) => {
        if (res && res.code === 200) {
          this.templates = res.data || [];
        }
      });
    },

    // 进入问卷编辑页面
    goToEditPage(id) {
      uni.navigateTo({
        url: `/pages/quest/edit?id=${id}`,
      });
    },

    // 显示创建弹窗
    showCreatePopup() {
      this.isEdit = false;
      this.formData = {
        id: "",
        title: "",
        description: "",
      };
      this.showFormPopup = true;
    },

    // 编辑问卷基本信息
    editQuestionnaire(item) {
      this.isEdit = true;
      this.formData = {
        id: item.id,
        title: item.title,
        description: item.description,
      };
      this.showFormPopup = true;
    },

    // 预览问卷
    previewQuestionnaire(item) {
      uni.navigateTo({
        url: `/pages/quest/preview?id=${item.id}`,
      });
    },

    // 切换更多菜单显示
    toggleMoreMenu(id) {
      this.showMoreMenu = this.showMoreMenu === id ? null : id;
    },

    // share
    // share
    share(id) {
      // 构建分享链接
      const shareUrl = `https://survy.z550.com/?id=${id}`;

      // 复制到剪贴板
      uni.setClipboardData({
        data: shareUrl,
        success: () => {
          // #ifdef APP-PLUS
          uni.share({
            provider: 'weixin',
            scene: 'WXSceneSession',
            type: 0,
            title: '用户满意度调查问卷',
            summary: '邀请您参与产品体验调研...',
            imageUrl: 'https://example.com/survey.jpg',
            href: 'https://example.com/survey?id=12345',
            success: function (res) {
              console.log("分享成功：" + JSON.stringify(res));
            },
            fail: function (err) {
              console.log("分享失败：" + JSON.stringify(err));
            }
          });
          // #endif

          // #ifdef MP-WEIXIN
          uni.share({
            provider: 'weixin',
            scene: 'WXSceneSession', // 分享到聊天
            type: 0,
            title: '分享标题',
            summary: '分享描述',
            imageUrl: '/static/share.jpg',
            href: 'https://example.com/path',
            success: (res) => {
              console.log('分享成功', res);
            },
            fail: (err) => {
              console.log('分享失败', err);
            }
          });
          // #endif

        },
        fail: () => {
          uni.showToast({
            title: "复制失败，请手动复制",
            icon: "none",
            duration: 2000,
          });
          // 如果复制失败，仍然显示链接让用户可以手动复制
          uni.showModal({
            title: "问卷链接",
            content: shareUrl,
            showCancel: false,
          });
        },
      });

      // 关闭菜单
      this.showMoreMenu = null;
    },

    // 复制问卷
    copyQuestionnaire(item) {
      this.currentItem = item;
      this.copyShow = true;
      this.copyValue = item.title + "（副本）";
      this.showMoreMenu = null;
      this.copyTemplate = false;
    },

    // 重命名问卷
    renameQuestionnaire(item) {
      this.currentItem = item;
      this.renameShow = true;
      this.renameValue = item.title;
      this.showMoreMenu = null;
    },

    // 处理重命名确认
    async handleRenameConfirm(newTitle) {
      this.renameLoading = true;
      try {
        await this.sjuAjax.post("/questionnaire/rename", {
          id: this.currentItem.id,
          title: newTitle,
        });
        uni.showToast({
          title: "重命名成功",
          icon: "success",
        });
        this.getQuestionnaireList();
      } finally {
        this.renameLoading = false;
      }
    },

    // 处理复制确认（现在也用于模板）
    async handleCopyConfirm(newTitle) {
      this.copyLoading = true;
      try {
        await this.sjuAjax.post("/questionnaire/copy", {
          id: this.currentItem.id,
          title: newTitle,
          is_template: this.currentItem.is_template,
        });
        uni.showToast({
          title: this.currentItem.is_template ? "使用模板成功" : "复制成功",
          icon: "success",
        });
        this.getQuestionnaireList();
      } finally {
        this.copyLoading = false;
        this.copyShow = false;
      }
    },

    // 取消重命名
    handleRenameCancel() {
      this.renameShow = false;
    },

    // 取消复制
    handleCopyCancel() {
      this.copyShow = false;
    },

    // 删除问卷
    deleteQuestionnaire(id) {
      this.sjuAlert.showConfirm(
        "确定要删除该问卷吗？\n删除后不可恢复！",
        () => {
          // 确定操作
          this.sjuAjax.post("/questionnaire/delete", { id }, (res) => {
            if (res && res.code === 200) {
              uni.showToast({
                title: "问卷已删除",
                icon: "success",
              });
              this.getQuestionnaireList();
            }
          });
        },
        () => {
          // 取消操作
          this.showMoreMenu = null;
        }
      );
    },

    // 使用模板创建问卷
    useTemplate(template) {
      this.currentItem = template;
      this.copyShow = true;
      this.copyValue = template.title + "（使用模板）";
      this.copyTemplate = true;
    },

    // 预览模板
    previewTemplate(template) {
      uni.navigateTo({
        url: `/pages/quest/preview?id=${template.id}`,
      });
    },

    // 提交表单
    handleSubmit(formData) {
      if (!formData.title) {
        uni.showToast({
          title: "请输入问卷标题",
          icon: "none",
        });
        return;
      }

      this.loading = true;

      const api = this.isEdit
        ? "/questionnaire/update"
        : "/questionnaire/create";
      const successMsg = this.isEdit ? "修改成功" : "创建成功";

      this.sjuAjax.post(
        api,
        formData,
        (res) => {
          this.loading = false;
          if (res && res.code === 200) {
            uni.showToast({
              title: successMsg,
              icon: "success",
            });
            this.showFormPopup = false;
            this.getQuestionnaireList();
          }
        },
        () => {
          this.loading = false;
        }
      );
    },
  },
};
</script>

<style lang="scss">
.questionnairePage {
  width: 100vw;
  height: 100vh;
  background-color: var(--v-bg);
  display: flex;
  flex-direction: column;
}


/* 顶部区域 */
.top {
  width: 100vw;
  height: 360rpx;
  background: var(--v-linear);
  flex-shrink: 0;
  border-radius: 0 0 30rpx 30rpx;

  .info {
    display: flex;
    align-items: center;
    display: flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    flex-direction: column;

    /* 右侧信息 */
    .info-right {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;

      .name {
        margin-bottom: 10rpx;
      }

      .name {
        font-size: 44rpx;
        letter-spacing: 4rpx;
        color: #fff;
        text-shadow: 4rpx 4rpx 8rpx rgba(0, 0, 0, 0.4);
        line-height: 1.2;
      }

      .company {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.9);
        text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
      }
    }
  }
}

.tabContainer {
  position: relative;
  top: -50rpx;
  margin: 0 30rpx;
}

/* 主内容区域 */
.main {
  position: relative;
  top: -50rpx;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  height: 0;

  .listBox {
    margin-top: 20rpx;
    padding: 0 30rpx;

    .questionnaireList,
    .templateList {
      .emptyTips {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 60rpx 0;
        color: #999;

        .emptyText {
          margin-top: 20rpx;
          font-size: 28rpx;
        }
      }
    }
  }
}

/* 创建问卷按钮 */
.createBtnFixed {
  position: fixed;
  bottom: 60rpx;
  left: 50%;
  transform: translateX(-50%);
  background: var(--v-theme);
  color: #fff;
  padding: 16rpx 40rpx;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 20rpx rgba(71, 197, 196, 0.4);
  z-index: 10;

  text {
    margin-left: 10rpx;
    font-size: 28rpx;
  }
}
</style>